#!/usr/bin/env bash
# Create a virtual bridge with PXE services and matchbox
# USAGE: ./scripts/devnet create [example]
# USAGE: ./scripts/devnet status
# USAGE: ./scripts/devnet destroy
set -u

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

EXAMPLE=${2:-}
# Local Container Runtime (docker)
CONTAINER_RUNTIME="${CONTAINER_RUNTIME:-docker}"
BRIDGE=metal0
ASSETS_DIR="${ASSETS_DIR:-$PWD/examples/assets}"
CONFIG_DIR="${CONFIG_DIR:-$PWD/examples/etc/matchbox}"

MATCHBOX_ARGS=""

if [ "$EUID" -ne 0 ]
  then echo "Please run as root"
  exit
fi

function main {
  if [ "$#" -eq 0 ]; then
    usage
    exit 2
  fi
  case "$1" in
    "create") create;;
    "status") status;;
    "destroy") destroy;;
    *)
      usage
      exit 2
      ;;
  esac
}

function usage {
  echo "USAGE: ${0##*/} <command>"
  echo "Commands:"
  echo -e "\tcreate\tcreate matchbox and PXE services on the bridge"
  echo -e "\tstatus\tshow the status of matchbox and dnsmasq"
  echo -e "\tdestroy\tdestroy the services on the bridge"
}

function create {
  case "$CONTAINER_RUNTIME" in
    "docker") docker_create;;
    *) docker_create;;
  esac
}

function status {
  case "$CONTAINER_RUNTIME" in
    "docker") docker_status;;
    *) docker_status;;
  esac
}

function destroy {
  case "$CONTAINER_RUNTIME" in
    "docker") docker_destroy;;
    *) docker_destroy;;
  esac
}

function docker_create {
  if [ -z "$EXAMPLE" ]; then
    echo "Starting matchbox"
  else
    echo "Starting matchbox configured to boot $EXAMPLE"
  fi

  if [ -z "$EXAMPLE" ]; then
    # Mount a data volume with assets and enable gRPC
    MATCHBOX_ARGS="-rpc-address=0.0.0.0:8081"
    DATA_MOUNT=""
  else
    # Mount the given EXAMPLE
    DATA_MOUNT="-v $PWD/examples:/var/lib/matchbox:Z -v $DIR/../examples/groups/$EXAMPLE:/var/lib/matchbox/groups:Z"
  fi

  docker run --name matchbox \
    -d \
    -p 8080:8080 \
    -p 8081:8081 \
    -v $CONFIG_DIR:/etc/matchbox:Z \
    -v $ASSETS_DIR:/var/lib/matchbox/assets:Z \
    $DATA_MOUNT \
    quay.io/poseidon/matchbox:latest -address=0.0.0.0:8080 -log-level=debug $MATCHBOX_ARGS

  echo "Starting dnsmasq to provide DHCP/TFTP/DNS services"
  docker run --name dnsmasq \
    -d \
    --cap-add=NET_ADMIN \
    -v $PWD/contrib/dnsmasq/docker0.conf:/etc/dnsmasq.conf:Z \
    quay.io/poseidon/dnsmasq:f4623c508ff3fbc467285de1ede61126624b91ac -d
}

function docker_status {
  docker logs matchbox
  docker logs dnsmasq
}

function docker_destroy {
  docker stop matchbox
  docker stop dnsmasq
  docker rm matchbox
  docker rm dnsmasq
}

main $@
